import {getValue} from './ext';
import { Lang } from './lang.pro';

type FieldValid = {
  field:string
  desc:string
  valids:("required"|((v:any,values:{[key:string]:any})=>true|string))[]
}

export class ValidTools{
  private validCfg:FieldValid[];
  constructor(param:FieldValid[]){
    let idx;
    param.forEach(m=>{
      idx = m.valids.indexOf('required');
      idx > -1 && m.valids.splice(idx,1) && m.valids.unshift('required');
    })
    this.validCfg = param;
  }

  async valid(values:{[key:string]:any}){
    const result:{[key:string]:boolean|string} = {};
    let vr:(true|string),flag = true;
    for(const m of this.validCfg){
      for(const n of m.valids){
        const v = getValue(values,m.field);
        //允许非空，值为空时,直接pass
        if(n=='required'){
          vr = this.required(v,`${m.desc}${Lang.notBlank}`);
        }else if(v==null){
          result[m.field]=true;
          break;
        }else  {
          vr = await n(v,values);
        }
        if(vr!=true){
          flag = false;
          result[m.field]=vr;
          break;
        }else{
          result[m.field]=true;
        }
      }
    }console.log(result)
    return [flag,result];
  }

  private required(v:any,desc:string):(true|string){
    return (v==null||v=='')?desc:true;
  }
}